package com.lemon.smartsafetynew.ui.activity.record;

import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lemon.android.http.HttpUtils;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.listener.RecyclerTClickListener;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.LemonFileHelper;
import com.lemon.smartsafetynew.entity.FileInfo;
import com.lemon.smartsafetynew.entity.event.incident.MediaEvent;
import com.lemon.smartsafetynew.entity.materiel.MaterialVo;
import com.lemon.smartsafetynew.entity.patrol.SafePatrolMediaVo;
import com.lemon.smartsafetynew.ui.activity.base.SwipeBackActivity;
import com.lemon.smartsafetynew.ui.adapter.incident.IncidentAttachmentAdapter;
import com.lemon.smartsafetynew.ui.adapter.record.FilesAdapter;
import com.lemon.smartsafetynew.util.common.CommonUtil;
import com.lemon.smartsafetynew.util.constants.KeyConstants;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.Bind;
import cn.finalteam.galleryfinal.model.PhotoInfo;


/**
 * 物料详情
 * Created by JiangAn on 2018/5/24.
 */

public class RecordMaterialDetailActivity extends SwipeBackActivity implements RecyclerTClickListener<FileInfo> {
    @Bind(R.id.iv_return)
    ImageView ivReturn;
    @Bind(R.id.tv_material_name)
    TextView tvMaterialName;
    @Bind(R.id.tv_material_type)
    TextView tvMaterialType;
    @Bind(R.id.tv_material_store_position)
    TextView tvMaterialStorePosition;
    @Bind(R.id.tv_material_store_metnod)
    TextView tvMaterialStoreMetnod;
    @Bind(R.id.tv_material_year_maker)
    TextView tvMaterialYearMaker;
    @Bind(R.id.tv_material_max_store)
    TextView tvMaterialMaxStore;
    @Bind(R.id.tv_cas_no)
    TextView tvCasNo;
    @Bind(R.id.tv_material_danger_type)
    TextView tvMaterialDangerType;
    @Bind(R.id.tv_material_danger_level)
    TextView tvMaterialDangerLevel;
    @Bind(R.id.tv_material_status)
    TextView tvMaterialStatus;
    @Bind(R.id.tv_isLiscense)
    TextView tvIsLiscense;
    @Bind(R.id.tv_is_toxic_chemic)
    TextView tvIsToxicChemic;
    @Bind(R.id.tv_isEasyMakeChemic)
    TextView tvIsEasyMakeChemic;
    @Bind(R.id.tv_isEasyMakerBomb)
    TextView tvIsEasyMakerBomb;
    @Bind(R.id.tv_isPonitMonitor)
    TextView tvIsPonitMonitor;
    @Bind(R.id.tv_space_remark)
    TextView tvSpaceRemark;
    @Bind(R.id.ryMaterial)
    RecyclerView ryMaterial;
    @Bind(R.id.ryMaterialFile)
    RecyclerView ryMaterialFile;

    private static MaterialVo data;
    @Bind(R.id.ll_status)
    LinearLayout llStatus;
    @Bind(R.id.ll_isliscence)
    LinearLayout llIsliscence;
    private Boolean isShowReturn = false;
    // ============ RecyclerView =============
    private IncidentAttachmentAdapter mMediaAdapter;

    @Override
    protected void initTitle() {
        this.setBarTitle(getString(R.string.record_material));
    }

    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            data = (MaterialVo) bundle.getSerializable(KeyConstants.KEY_MATERIAL_VO);
            isShowReturn = bundle.getBoolean("isShowReturn");
        }
    }

    @Override
    protected void callFinish() {
        AppManager.getAppManager().finishActivity(RecordMaterialDetailActivity.this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_record_material_detail;
    }

    @Override
    protected void initViews() {
        super.initViews();
        if (isShowReturn) {
            ivReturn.setVisibility(View.VISIBLE);
        } else {
            ivReturn.setVisibility(View.INVISIBLE);
        }
        if (data != null) {
            tvMaterialName.setText(CommonUtil.avoidNullString(data.getName()));
            tvMaterialType.setText(CommonUtil.avoidNullString(data.getType()));
            tvMaterialStorePosition.setText(CommonUtil.avoidNullString(data.getPosition()));
            tvMaterialStoreMetnod.setText(CommonUtil.avoidNullString(data.getStorageMode()));
            tvMaterialYearMaker.setText(CommonUtil.avoidNullString(data.getAnnualOutput()));
            tvMaterialMaxStore.setText(CommonUtil.avoidNullString(data.getMaxReserves()));
            tvCasNo.setText(CommonUtil.avoidNullString(data.getCas()));
            tvMaterialDangerType.setText(CommonUtil.avoidNullString(data.getDangerousChemicals()));
            tvMaterialDangerLevel.setText(CommonUtil.avoidNullString(data.getHazardous()));
            if (!TextUtils.isEmpty(data.getType())) {
                if ("原料".equals(data.getType())) {
                    llIsliscence.setVisibility(View.GONE);
                    llStatus.setVisibility(View.GONE);
                } else {
                    llIsliscence.setVisibility(View.VISIBLE);
                    llStatus.setVisibility(View.VISIBLE);
                    tvMaterialStatus.setText(CommonUtil.avoidNullString(data.getStatus()));
                    tvIsLiscense.setText(CommonUtil.avoidNullString(data.getIsLicence()));
                }
            }
            tvIsToxicChemic.setText(CommonUtil.avoidNullString(data.getIsToxic()));
            tvIsEasyMakeChemic.setText(CommonUtil.avoidNullString(data.getIsChemicals()));
            tvIsEasyMakerBomb.setText(CommonUtil.avoidNullString(data.getIsBomb()));
            tvIsPonitMonitor.setText(CommonUtil.avoidNullString(data.getIsSupervision()));
            tvSpaceRemark.setText(CommonUtil.avoidNullString(data.getRemark()));
            initAdapter();
        }
    }

    private void initAdapter() {
        if (!TextUtils.isEmpty(data.getPicture())) {
            List<String> idList = Arrays.asList(data.getPicture().split(","));
            List<SafePatrolMediaVo> photoVo = new ArrayList<>();
            for (int i = 0; i < idList.size(); i++) {
                SafePatrolMediaVo safePatrolMediaVo = new SafePatrolMediaVo();
                safePatrolMediaVo.setData_url(idList.get(i));
                photoVo.add(safePatrolMediaVo);
            }
            GridLayoutManager gridLayoutManager = new GridLayoutManager(RecordMaterialDetailActivity.this, 3);
            ryMaterial.setLayoutManager(gridLayoutManager);
            ryMaterial.setNestedScrollingEnabled(false);
            mMediaAdapter = new IncidentAttachmentAdapter(photoVo, RecordMaterialDetailActivity.class.getName());
            ryMaterial.setAdapter(mMediaAdapter);
        }
        if (!TextUtils.isEmpty(data.getFile())) {
            List<String> list = Arrays.asList(data.getFile().split(","));//根据逗号分隔转化为list
            List<FileInfo> fileList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                FileInfo fileinfo = new FileInfo();
                fileinfo.setName("附件一");
                fileinfo.setUrl(HttpUtils.formatFilesUrl(data.getFile()));
                fileList.add(fileinfo);
            }
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(RecordMaterialDetailActivity.this);
            linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            ryMaterialFile.setLayoutManager(linearLayoutManager);
            ryMaterialFile.setNestedScrollingEnabled(false);
            FilesAdapter mAdapter = new FilesAdapter(fileList, this);
            ryMaterialFile.setAdapter(mAdapter);
        }
    }

    @Override
    protected void initListener() {
        super.initListener();
        ivReturn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppManager.getAppManager().finishActivity(RecordMaterialDetailActivity.this);
                AppManager.getAppManager().finishActivity(MaterielActivity.class);
            }
        });
    }

    /**
     * 显示图片和音频详情
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMediaEvent(MediaEvent event) {

        if (RecordMaterialDetailActivity.class.getName().equals(event.getTag())) {

            SafePatrolMediaVo data = event.getMediaVos().get(event.getPosition());

            if (LemonFileHelper.isImageUrl(data.getData_url())) {
                List<SafePatrolMediaVo> mediaVos = event.getMediaVos();
                List<PhotoInfo> photos = new ArrayList<>();

                int j = 0;
                int currentItem = 0;

                for (int i = 0; i < mediaVos.size(); i++) {
                    if (LemonFileHelper.isImageUrl(mediaVos.get(i).getData_url())) {

                        if (data.getData_url().equals(mediaVos.get(i).getData_url())) {
                            currentItem = j;
                        }

                        PhotoInfo photoInfo = new PhotoInfo();
                        photoInfo.setPhotoId(j);
                        photoInfo.setPhotoPath(HttpUtils.formatFilesUrl(mediaVos.get(i).getData_url()));
                        photos.add(photoInfo);
                        j++;
                    }
                }

                if (photos != null && photos.size() != 0) {
                    UIHelper.showPhotoView(this, photos, currentItem);
                }
            } else if (LemonFileHelper.isVoiceUrl(data.getData_url())) {
                playVoice(HttpUtils.formatFilesUrl(data.getData_url()));
            }

        }
    }

    @Override
    public void onItemClick(FileInfo data, int position) {
        downloadAndShowFile(data.getUrl(), data.getName(), this, getResources().getString(R.string.record_material));
    }
}


